﻿CREATE PROCEDURE [dbo].[AddEntity]
	@entity_type_id int,
	@name varchar(64),
	@parent_id int = 0,
	@top_level_id int = 0
AS
	declare @result int;
	IF EXISTS(select entity_id from dbo.Entity where entity_type_id = @entity_type_id and name = @name and parent_id = @parent_id and top_level_id = @top_level_id)
	BEGIN
		-- Entity already exists, update it and return ID
		select @result = entity_id from dbo.Entity where entity_type_id = @entity_type_id and name = @name and parent_id = @parent_id and top_level_id = @top_level_id;
	END
	ELSE
	BEGIN

		insert into dbo.Entity (entity_type_id, name, parent_id, top_level_id)
			values (@entity_type_id, @name, @parent_id, @top_level_id);
		select @result = SCOPE_IDENTITY();
	END
select @result
